﻿using System;
using System.Collections.Generic;
using System.Linq;

using Csla.Security;

using Haushaltsbuch.DataAcces;
using Haushaltsbuch.Domain.Authentication;
using Haushaltsbuch.Domain.Users;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using FluentAssertions;

namespace Haushaltsbuch.Tests
{
    [TestClass]
    public class UserTests
    {
        [ClassInitialize] public static void Initialize(TestContext context)
        {
            TestHelpers.InitDbForTest();
        }
        [TestCleanup] public void Cleanup()
        {
            HaushaltsbuchPrincipal.Logout();
        }

        [TestMethod] public void Get_List_of_all_Users()
        {
            TestHelpers.LoginAsAdmin();
            var userInfoList = UserInfoList.Get();

            using (var ctx = new HaushaltsbuchContext())
            {
                var actualUsers = ctx.Users.ToArray();
                userInfoList.ShouldBeEquivalentTo(actualUsers, o => o.ExcludingMissingProperties());
            }
        }
        [TestMethod] public void Get_List_of_all_Users_Withoutpermission()
        {
            TestHelpers.LoginAsReader();
            Action getUsers =() => UserInfoList.Get();

            getUsers.ShouldThrow<SecurityException>();

        }
        [TestMethod] public void Get_Editable_User()
        {
            TestHelpers.LoginAsAdmin();

            using (var ctx = new HaushaltsbuchContext())
            {
                var idMax = ctx.Users.Select(u => u.Id).Max();
                var dbUser = ctx.Users.Find(idMax);
                var user = UserEdit.Get(idMax);

                user.ShouldBeEquivalentTo(dbUser, o => o.ExcludingMissingProperties());
            }
        }
        [TestMethod] public void Get_Editable_User_WithOutPermission()
        {
            TestHelpers.LoginAsReader();

            using (var ctx = new HaushaltsbuchContext())
            {
                var idMax = ctx.Users.Select(u => u.Id).Max();
                var dbUser = ctx.Users.Find(idMax);
                Action getUsers =() =>  UserEdit.Get(idMax);
                getUsers.ShouldThrow<SecurityException>();
                
            }
        }



    }
}